﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Aierp.SystemEntities.System;
using Aierp.SystemRepository.Implements;
using Aierp.Utility.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using ControllerBase = Aierp.Controllers.ControllerBase;

namespace Aierp.SystemControllers
{
    [Route("api/[controller]")]
    public class NavButtonsController : ControllerBase
    {
        NavButtonsRepository Repository { get; set; }
        SysVisitor SysVisitor { get; set; }
        public NavButtonsController(NavButtonsRepository navButtonsRepository, SysVisitor sysVisitor)
        {
            Repository = navButtonsRepository;
            SysVisitor = sysVisitor;
        }

        [HttpGet("{id}")]
        public async Task Get(int id)
        {
            var model = Repository.FindByNavId(id);
            if (model == null)
            {
                await WriteFailJson();
                return;
            }
            await WriteResultJson(model);
        }


        /// <summary>
        /// 获取按钮列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetList")]
        public async Task GetList()
        {
            var pageParam = this.GetPageParam();
            await Response.WriteAsync(Repository.GetList(pageParam.Order, pageParam.Limit, pageParam.Offset, pageParam.SearchModel));
        }

        /// <summary>
        /// 添加按钮
        /// </summary>
        /// <returns></returns>
        [HttpPost("Add")]
        public async Task Add()
        {
            //获取按钮
            var model = GetModel<List<Sys_NavButtons>>();

            if (model.Count == 0)
            {
                await this.WriteSpecReasonJson("操作失败，每个菜单最少要保留一个默认浏览按钮！");
                return;
            }

            var navId = model[0].NavId;

            //先统一删除
            Repository.RemoveByNavId(navId);

            //查询--存在，则不处理；不存在，则添加；
            foreach (var s in model)
            {
                Repository.Add(s);
            }
            await this.WriteSucessJson();
        }

        /// <summary>
        /// 删除按钮--物理删除
        /// </summary>
        /// <param name="id"></param>
        // DELETE api/values/5
        [HttpDelete("{id}")]
        public async Task Delete(int id)
        {
            if (id == 0)
            {
                await this.WriteSpecReasonJson("内容不能为空！");
                return;
            }

            var result = Repository.RemoveByNavId(id);
            if (result > 0)
            {
                await this.WriteSucessJson();
                return;
            }

            //处理错误信息
            switch (result)
            {
                case -2:
                    await this.WriteSpecReasonJson("删除失败，错误信息如下：系统中找不到这个按钮！");
                    return;
                default:
                    await this.WriteSpecReasonJson("删除失败,请联系管理员！");
                    break;
            }
        }
    }
}
